<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生信息管理系统</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.0/font/bootstrap-icons.css">
    <style>
        .gender-icon {
            font-size: 1.2rem;
        }
        .male {
            color: #0d6efd;
        }
        .female {
            color: #dc3545;
        }
    </style>
</head>
<body>
<div class="container-fluid mt-3">
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">学生信息管理</h5>
            <button class="btn btn-primary" onclick="showAddModal()">
                <i class="bi bi-plus-lg"></i> 添加学生
            </button>
        </div>
        <div class="card-body">
            <div class="row mb-3">
                <div class="col-md-3">
                    <input type="text" id="searchName" class="form-control" placeholder="请输入姓名">
                </div>
                <div class="col-md-2">
                    <select id="searchGender" class="form-select">
                        <option value="">全部性别</option>
                        <option value="1">男</option>
                        <option value="0">女</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <button class="btn btn-outline-primary" onclick="loadData()">
                        <i class="bi bi-search"></i> 搜索
                    </button>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                    <tr>
                        <th>学号</th>
                        <th>姓名</th>
                        <th>性别</th>
                        <th>生日</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="studentTableBody">
                    <!-- 数据将通过Ajax动态加载 -->
                    </tbody>
                </table>
            </div>

            <nav>
                <ul class="pagination justify-content-center" id="pagination">
                    <!-- 分页将通过Ajax动态生成 -->
                </ul>
            </nav>
        </div>
    </div>
</div>

<!-- 添加/编辑模态框 -->
<div class="modal fade" id="studentModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">添加学生</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="studentForm">
                    <input type="hidden" id="studentNo">
                    <div class="mb-3">
                        <label for="name" class="form-label">姓名</label>
                        <input type="text" class="form-control" id="name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">性别</label>
                        <div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="gender" id="male" value="1" checked>
                                <label class="form-check-label" for="male">男</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="gender" id="female" value="0">
                                <label class="form-check-label" for="female">女</label>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="birthday" class="form-label">生日</label>
                        <input type="date" class="form-control" id="birthday">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveStudent()">保存</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    let currentPage = 1;
    const pageSize = 10;
    let modal = new bootstrap.Modal(document.getElementById('studentModal'));

    // 页面加载时获取数据
    $(document).ready(function() {
        loadData();
    });

    // 加载学生数据
    function loadData(page = 1) {
        currentPage = page;
        const name = $('#searchName').val();
        const gender = $('#searchGender').val();

        $.ajax({
            url: '/api/students/page',
            type: 'GET',
            data: {
                current: page,
                size: pageSize,
                name: name,
                gender: gender
            },
            success: function(res) {
                if (res.success) {
                    renderTable(res.data);
                    renderPagination({
                        current: res.current,
                        pages: res.pages,
                        hasPrevious: res.current > 1,
                        hasNext: res.current < res.pages
                    });
                } else {
                    alert(res.message);
                }
            },
            error: function(xhr) {
                const errorMsg = xhr.responseJSON?.message || xhr.statusText;
                alert('请求失败: ' + errorMsg);
                console.error('Error details:', xhr.responseJSON);
            }
        });
    }

    // 渲染表格数据
    function renderTable(students) {
        const tbody = $('#studentTableBody');
        tbody.empty();

        if (!students || students.length === 0) {
            tbody.append('<tr><td colspan="6" class="text-center">暂无数据</td></tr>');
            return;
        }

        students.forEach(student => {
            const genderIcon = student.gender === '1' ?
                '<i class="bi bi-gender-male gender-icon male"></i>' :
                '<i class="bi bi-gender-female gender-icon female"></i>';

            const genderText = student.gender === '1' ? '男' : '女';
            const birthday = student.birthday ? formatDate(student.birthday) : '--';
            const createTime = student.createTime ? formatDateTime(student.createTime) : '--';

            const row = `
                <tr>
                    <td>${student.studentNo}</td>
                    <td>${student.name}</td>
                    <td>${genderIcon} ${genderText}</td>
                    <td>${birthday}</td>
                    <td>${createTime}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick="showEditModal(${student.studentNo})">
                            <i class="bi bi-pencil"></i> 编辑
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteStudent(${student.studentNo})">
                            <i class="bi bi-trash"></i> 删除
                        </button>
                    </td>
                </tr>
            `;
            tbody.append(row);
        });
    }

    // 格式化日期 (yyyy-MM-dd)
    function formatDate(dateStr) {
        if (!dateStr) return '--';
        const date = new Date(dateStr);
        return date.toISOString().split('T')[0];
    }

    // 格式化日期时间 (yyyy-MM-dd HH:mm:ss)
    function formatDateTime(dateTimeStr) {
        if (!dateTimeStr) return '--';
        const date = new Date(dateTimeStr);
        return date.toLocaleString('zh-CN');
    }

    // 渲染分页
    function renderPagination(pageInfo) {
        const pagination = $('#pagination');
        pagination.empty();

        if (pageInfo.pages <= 1) return;

        // 上一页
        if (pageInfo.hasPrevious) {
            pagination.append(`
                <li class="page-item">
                    <a class="page-link" href="javascript:void(0)" onclick="loadData(${currentPage - 1})">
                        <i class="bi bi-chevron-left"></i>
                    </a>
                </li>
            `);
        }

        // 页码
        for (let i = 1; i <= pageInfo.pages; i++) {
            const active = i === currentPage ? 'active' : '';
            pagination.append(`
                <li class="page-item ${active}">
                    <a class="page-link" href="javascript:void(0)" onclick="loadData(${i})">${i}</a>
                </li>
            `);
        }

        // 下一页
        if (pageInfo.hasNext) {
            pagination.append(`
                <li class="page-item">
                    <a class="page-link" href="javascript:void(0)" onclick="loadData(${currentPage + 1})">
                        <i class="bi bi-chevron-right"></i>
                    </a>
                </li>
            `);
        }
    }

    // 显示添加模态框
    function showAddModal() {
        $('#modalTitle').text('添加学生');
        $('#studentForm')[0].reset();
        $('#studentNo').val('');
        modal.show();
    }

    // 显示编辑模态框
    function showEditModal(studentNo) {
        $.ajax({
            url: '/api/students/' + studentNo,
            type: 'GET',
            success: function(res) {
                if (res.success) {
                    $('#modalTitle').text('编辑学生');
                    $('#studentNo').val(res.data.studentNo);
                    $('#name').val(res.data.name);
                    $(`input[name="gender"][value="${res.data.gender}"]`).prop('checked', true);
                    $('#birthday').val(res.data.birthday ? formatDate(res.data.birthday) : '');
                    modal.show();
                } else {
                    alert(res.message);
                }
            },
            error: function(xhr) {
                const errorMsg = xhr.responseJSON?.message || xhr.statusText;
                alert('请求失败: ' + errorMsg);
            }
        });
    }

    // 保存学生信息
    function saveStudent() {
        const studentNo = $('#studentNo').val();
        const student = {
            studentNo: studentNo || null,
            name: $('#name').val(),
            gender: $('input[name="gender"]:checked').val(),
            birthday: $('#birthday').val()
        };

        if (!student.name) {
            alert('请输入姓名');
            return;
        }

        const url = studentNo ? '/api/students/' + studentNo : '/api/students';
        const method = studentNo ? 'PUT' : 'POST';

        $.ajax({
            url: url,
            type: method,
            contentType: 'application/json',
            data: JSON.stringify(student),
            success: function(res) {
                alert(res.message);
                if (res.success) {
                    modal.hide();
                    loadData(currentPage);
                }
            },
            error: function(xhr) {
                const errorMsg = xhr.responseJSON?.message || xhr.statusText;
                alert('请求失败: ' + errorMsg);
            }
        });
    }

    // 删除学生
    function deleteStudent(studentNo) {
        if (!confirm('确定要删除该学生吗？')) return;

        $.ajax({
            url: '/api/students/' + studentNo,
            type: 'DELETE',
            success: function(res) {
                alert(res.message);
                if (res.success) {
                    loadData(currentPage);
                }
            },
            error: function(xhr) {
                const errorMsg = xhr.responseJSON?.message || xhr.statusText;
                alert('请求失败: ' + errorMsg);
            }
        });
    }
</script>
</body>
</html>